package com.tnt.jxls;

import lombok.extern.slf4j.Slf4j;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhuangxl
 * @description
 * @since 2021-03-27 22:04
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class Test {

    @GetMapping("/export")
    public String export(HttpServletRequest request, HttpServletResponse response) {
        String exportTempName = "用户列表导出模板.xlsx";
        String exportFileName = "用户列表导出.xlsx";
        try {
            //获取数据
            List<User> users = new ArrayList<>();
            for(int i=0;i < 10;i++){
                User user = new User();
                user.setId(RandomUtil.getRandomLong(6));
                user.setName(RandomUtil.getRandomJianHan(3));
                user.setAge(RandomUtil.getRandomInt(10, 100));
                user.setEmail(RandomUtil.getRandomCharacter(6)+"@qq.com");
                users.add(user);
            }


            //设置jxls相关信息
            Context context = new Context();
            context.putVar("users", users);
            context.putVar("title","用户列表导出");
            context.putVar("exportDate", LocalDateTime.now());
            context.putVar("exportUser", RandomUtil.getRandomChinese(3));

            //加载模板
            InputStream exIs = this.getClass().getResourceAsStream("/"+exportTempName);
            //生成导出文件
            File tempFile = new File(System.getProperty("java.io.tmpdir") + File.separator + System.currentTimeMillis());
            OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile));
            JxlsHelper.getInstance().processTemplate(exIs, os, context);
            //导出下载
            InputStream is = new BufferedInputStream(new FileInputStream(tempFile));
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            is.close();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(exportFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            response.addHeader("Content-Length", "" +tempFile.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件下载出错";
        }
    }

    @GetMapping("/read")
    public String read(HttpServletRequest request, HttpServletResponse response) throws Exception{


        InputStream inputXML = new BufferedInputStream(getClass().getResourceAsStream("/xmlConfig.xml"));
        XLSReader mainReader = ReaderBuilder.buildFromXML( inputXML );
        InputStream inputXLS = new BufferedInputStream(getClass().getResourceAsStream("/data.xlsx"));

        Map<String, Object> beans = new HashMap<>();
        AreaTitle areaTitle = new AreaTitle();
        List<Area> areas = new ArrayList<>();
        beans.put("areaTitle", areaTitle);
        beans.put("list", areas);
        XLSReadStatus readStatus = mainReader.read(inputXLS, beans);
        log.info("result:{}", beans);

        return "123";

    }
}
